<template>

	<view class="bg" :style="{ '--bg-image': `url(${ bargainPriceBg})` }">
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="downOption" @down="downCallback" @up="upCallback">
			<view class="flex-between">


				<view class="return-index flex" @click="returnHome()" v-if="shareList.length">

					<swiper class="swiper" :autoplay='autoplayBoolen' vertical=true circular
						:indicator-dots="indicatorDots" :duration="duration">
						<block v-for="(item,i) in shareList" :key="i">
							<swiper-item>
								<view class="swiper-item uni-bg-red flex">
									<image class="noticeImg" :src="item.avatar" mode="aspectFill"></image>

									<text class="font-overflow"
										style="color: #fff;font-size: 26rpx;max-width: 260rpx;">{{item.content}}
									</text>
								</view>

							</swiper-item>
						</block>

					</swiper>


				</view>

			</view>
			<view class="card">
				<view class="pendingPayDetail">
					<view class="orderPageDescribe flex-start">
						<view>
							<image class="img" :src="detailInfo.pic_url" mode=""></image>
						</view>
						<view class="flex-columns margin-left_20rpx" style="height: 175rpx;width:414rpx;">
							<view class="">
								<view class="font-overflow font-weight_bold">
									{{detailInfo.goods_name}}
								</view>
								<view class="font-overflow "
									style="width: 100%; color: rgb(153, 153, 153);margin-top: 10rpx;">
									<text style="font-size: 24rpx;">{{detailInfo.spec_name}}</text>
								</view>
							</view>




							<view class="example-body">
								<view style="color: #FF0000;display: flex; align-items: baseline;" class="">
									<text style="font-size: 24rpx;">当前砍到 </text><text
										style="font-size: 36rpx;font-weight: 700;">￥{{detailInfo.order_money}}</text>
								</view>
							</view>


						</view>
					</view>


				</view>
				<view class="initiateBargaining flex margin_40rpx_0" v-if="assistUid!=uid&&!cutDetail.cutCount"
					@click="joinActivities(3,detailInfo.id)">
					我也参与购买，发起砍价
				</view>
				
				<view class="initiateBargaining flex margin_40rpx_0" v-if="assistUid!=uid&&cutDetail.cutCount" @click="cutYourselfKnife()">
					当前还可以帮好友在砍 <text style="color: #FF1200;margin: 0 5rpx;">{{cutDetail.cutCount}}</text> 刀
				</view>
				<button open-type="share" class="btncss">
					
					
					<view class="text-align_center margin-top_30rpx" v-if="assistUid!=uid&&!cutDetail.cutCount">
						您已经帮他砍过了，分享给好友帮他一起砍>
					</view>
				</button>


				<view class="margin-top_30rpx text-align_center" v-if="assistUid==uid">
					<block>
						<view class="font-weight_bold margin-bottom_30rpx">
							已砍<text>{{((Number(detailInfo.price)- Number(detailInfo.order_money))>(Number(detailInfo.price)- Number(detailInfo.money))?(Number(detailInfo.price)- Number(detailInfo.money)):(Number(detailInfo.price)- Number(detailInfo.order_money))).toFixed(2)}}</text>元，再砍<text
								style="color:#FF0000 ;">{{(((Number(detailInfo.order_money)- Number(detailInfo.money))<0)?(Number(0)):(Number(detailInfo.order_money)- Number(detailInfo.money))).toFixed(2)}}</text>元获得最低价
						</view>
						<view style="margin-top: 5rpx; " class="margin_20rpx_0 flex">
							<cc-countdown color="#FF1200" background-color="#FFE8E8" splitorColor="#FF1200"
								:showColon="true" :showDay="true" :day="detailInfo.timeDifference.days"
								:hour="detailInfo.timeDifference.hours" :minute="detailInfo.timeDifference.minutes"
								:second="detailInfo.timeDifference.seconds" @timeup="timeup"></cc-countdown>
							<view class="margin-left_10rpx" style="color: #EC486B;">
								后结束
							</view>
						</view>
						<view class="margin_20rpx_0">
							<ai-progress v-if="detailInfo.price"
								:percentage="((Number(detailInfo.price)- Number(detailInfo.order_money))>(Number(detailInfo.price)- Number(detailInfo.money))?(Number(detailInfo.price)- Number(detailInfo.money)):(Number(detailInfo.price)- Number(detailInfo.order_money))).toFixed(2)"
								:is-animate="true" :totalNum="Number(detailInfo.price)-Number(detailInfo.money)"
								duration="3000"></ai-progress>
							<!-- <ai-progress v-if="detailInfo.price"
							:percentage="(((Number(detailInfo.price)- Number(detailInfo.order_money))>(Number(detailInfo.price)- Number(detailInfo.money))?(Number(detailInfo.price)):(Number(detailInfo.price)- Number(detailInfo.order_money)))).toFixed(2)"
							:is-animate="true" :totalNum="Number(detailInfo.price)" duration="3000"></ai-progress> -->
						</view>
						<view class="" style="color: #FF0000;">
							点击下方按钮，邀请好友立即砍价拿到
						</view>

						<view class="initiateBargainingRed flex margin-top_30rpx"
							v-if="(Number(detailInfo.price)- Number(detailInfo.order_money))" @click="buy()">
							￥{{detailInfo.order_money}} 立即支付
						</view>
						<view class="initiateBargainingRed flex margin-top_30rpx" v-else @click="cutYourselfKnife()">
							已砍0.00元,可自砍一刀
						</view>
						<button open-type="share" class="btncss">
							<view class="text-align_center margin-top_30rpx">
								分享给好友一起砍>
							</view>
						</button>

					</block>

				</view>


			</view>
			<!-- 规则 -->
			<view class="rules" v-if="activitySetObj.bargains_desc">
				<view class="text-align_center font-weight_bold font-size_36rpx margin-bottom_30rpx">
					砍价规则
				</view>
				<uv-parse :content="activitySetObj.bargains_desc" :selectable="true"></uv-parse>
			</view>
		</mescroll-body>

		<sunui-popup ref="popCode">
			<template v-slot:content>
				<view class="v-pop-code">
					<view class="flex-column v-qr-code" @click="assistCk()">
						<image :src="mob8" mode="scaleToFill"></image>
						<view class="orderPageDescribe flex-start">
							<view>
								<image class="img" :src="detailInfo.pic_url" mode="">
								</image>
							</view>
							<view class="flex-column-between-start margin-left_20rpx"
								style="height: 125rpx;width:214rpx;">
								<view class="font-overflow" style="width:214rpx;">
									{{detailInfo.goods_name}}
								</view>
								<!-- <view class="font-overflow" style="width: 100%; color: rgb(153, 153, 153);">
									<text>独立多开加强版</text>
								</view> -->
								<view class="example-body">
									<view style="color: #FF0000;display: flex; align-items: baseline;" class="">
										<text style="font-size: 22rpx;">最低可砍 </text><text
											style="font-size: 22rpx;font-weight: 700;">￥{{detailInfo.money}}</text>
									</view>
								</view>


							</view>
						</view>
					</view>
					<!-- <view class="flex" @click="popCodeClose">
						<image class="v-close-img" src="/static/close.png"></image>
					</view> -->
				</view>
			</template>
		</sunui-popup>
	</view>
</template>

<script>
	import antiThrottling from '@/utils/antiThrottling.js';
	import aiProgress from '@/components/ai-progress/ai-progress.vue'
	export default {
		components: {
			aiProgress

		},
		data() {
			return {
				mob8: this.$imgs.mob8,
				duration: 1000,
				indicatorDots: false,
				autoplayBoolen: true,
				token: uni.getStorageSync('login').token,
				uid: uni.getStorageSync('uid'),
				list: [],
				bargainPriceBg: this.$imgs.bargainPriceBg,
				classifyList: [],
				shareList: [],
				navIndex: 0,
				tabList: [],
				orderInfo: null,
				activitType: '',
				detailInfo: {},
				assistUid: '',
				activitySetObj: {},
				bargains_id: '',
				uid: uni.getStorageSync('uid'),
				cutDetail:{}


			}
		},
		onLoad(options) {
			if (options.assistUid) {
				console.log(options)
				uni.setStorageSync('assistUid', options.assistUid);
				this.assistUid = options.assistUid
				this.bargains_id = options.bargains_id
				this.bargainsGoodsDetail(options.assistUid, options.bargains_id)
				this.activitType = 3


			} else {

				var pages = getCurrentPages(); //当前页
				var beforePage = pages[pages.length - 2]; //上个页面
				this.detailInfo = beforePage.$vm.detailInfo;
				this.activitType = beforePage.$vm.activitType
				console.log(this.detailInfo, this.activitType)
				this.assistUid = uni.getStorageSync('uid')
				this.bargains_id = this.detailInfo.id
				if (this.detailInfo.log.length) {
					this.shareList = this.detailInfo.log.map((item) => {
						return {
							userName: item.nickname,
							avatar: item.avatar,
							content: item.nickname + '帮砍了' + item.money + '元'
						}
					})
					console.log(this.shareList)
				}
			}
			// if (options.assistUid != uni.getStorageSync('uid')) {
			// 	this.popClick()
			// }


		},
		onShow() {
			antiThrottling.releaseKey('submit');
			this.activitySetFn()
			this.$nextTick(() => {
				this.mescroll?.resetUpScroll();
			})
		},
		methods: {
			async cutDetailFn(uid){
				const result = await this.$http.get({
					url: this.$api.cutDetail,
					data: {
				        uid:  uni.getStorageSync('uid'),
				        order_id: this.detailInfo.order_id
				
					}
				});
				if (result.errno == 0) {
				
					console.log(result.data)
					this.cutDetail=result.data
					
				
				}else{
					this.$sun.toast(result.message,'none')
				}
			},
			// 我的订单
			async upCallback(scroll) {
				this.mescroll.endByPage(1, 10);
				this.bargainsGoodsDetail(this.assistUid, this.bargains_id)
			},
			async activitySetFn() {
				const result = await this.$http.get({
					url: this.$api.activitySet,
					data: {



					}
				});
				if (result.errno == 0) {

					console.log(result.data)
					this.activitySetObj = result.data

				}
			},
			joinActivities(index, id) {
				this.$sun.navGo('/pages/detail/detail', {
					goods_id: id,
					type: index
				});
			},

			async assistCk() {
				// 判断当前是否登录
				if (this.handleLogin()) {
					antiThrottling.uniDoFunc({
						// 键名
						key: 'submit',
						success: async () => {
							//锁定
							antiThrottling.lockKey('submit');


							console.log('阻力', this.assistUid, this.detailInfo.order_id)
							const result = await this.$http.get({
								url: this.$api.bargainsBargainsCut,
								data: {
									uid: uni.getStorageSync('uid'),
									order_id: this.detailInfo.order_id
								}
							});
							if (result.errno == 0) {


								this.$sun.toast('砍价成功,已砍' + result.data, 'none')

								console.log(result)

								// this.bargainsGoodsDetail()
								antiThrottling.releaseKey('submit');

								this.$nextTick(() => {

									this.popCodeClose()

									setTimeout(() => {
										this.mescroll?.resetUpScroll();
									}, 500)
								})
							} else {
								this.$sun.toast(result.message);
								antiThrottling.lockKey('submit');
							}


						}
					});
				}


			},
			// 判断登录
			handleLogin() {
				if (this.uid) {
					return true;
				} else {
					uni.navigateTo({
						url: `/pages/login/login`
					});
				}
			},
			buy() {
				this.$nextTick(() => {
					this.mescroll?.resetUpScroll();
				})
				setTimeout(() => {
					uni.hideLoading()
					console.log('111')
					if (this.handleLogin()) {
						if (this.norms && this.norms.length > 0) {
							this.specClick(0, this.norms[0]);
							this.$refs.popbuy.show({
								anim: 'bottom',
								position: 'bottom',
								shadeClose: true, //false使用户不能点击其它关闭页面
								topclose: false
							});
						} else {
							this.$sun.navGo('/pages/confirmOrder/confirmOrder');
						}
					}
				},800)
			},
			
			
			
			onShareAppMessage(res) {
				console.log('/pages/activityPgae/bargainAssistancePage?assistUid=' + uni.getStorageSync("uid") +
					'&bargains_id=' + this.detailInfo.id)
				if (res.from === 'button') {
					if (this.assistUid == this.uid) {
						return {
							// 自定义分享标题
							title: this.detailInfo.share_title ? this.detailInfo.share_title : '邀请好友砍价',
							imageUrl: this.detailInfo.share_pic ? this.detailInfo.share_pic : '',
							path: '/pages/activityPgae/bargainAssistancePage?assistUid=' + uni.getStorageSync("uid") +
								'&bargains_id=' + this.detailInfo.id
						};
					} else {

						// 来自页面内分享按钮
						return {
							// 自定义分享标题
							title: this.detailInfo.share_title ? this.detailInfo.share_title : '邀请好友砍价',
							imageUrl: this.detailInfo.share_pic ? this.detailInfo.share_pic : '',
							path: '/pages/activityPgae/bargainAssistancePage?assistUid=' + uni.getStorageSync(
								"assistUid") + '&bargains_id=' + this.detailInfo.id
						};
					}
					this.addShare(this.detailInfo.id)

				} else {
					// path: '/pages/detail/detail?goods_id=' + this.detailInfo.id + '&uid=' + this.uid
					return {
						// 自定义分享标题
						title: this.detailInfo.share_title ? this.detailInfo.share_title : '邀请砍价',
						imageUrl: this.detailInfo.share_pic ? this.detailInfo.share_pic : '',
						path: '/pages/activityPgae/bargainAssistancePage?assistUid=' + uni.getStorageSync("uid") +
							'&bargains_id=' + this.detailInfo.id
					};
				}


			},
			async addShare(id) {
				const result = await this.$http.get({
					url: this.$api.addShareNumber,
					data: {
						// 产品id
						goods_id: id ? id : this.detailInfo.id
					}
				});
				if (result.errno == 0) {}
			},
			formatTimeDifference(timestamp) {
				// 获取当前时间的时间戳（以秒为单位）
				const currentTimestamp = Math.floor(Date.now() / 1000);

				// 计算时间差（以秒为单位）
				let timeDifference = timestamp - currentTimestamp;

				// 计算天数
				const days = Math.floor(timeDifference / (24 * 60 * 60));
				timeDifference %= (24 * 60 * 60);

				// 计算小时
				const hours = Math.floor(timeDifference / (60 * 60));
				timeDifference %= (60 * 60);

				// 计算分钟
				const minutes = Math.floor(timeDifference / 60);

				// 剩余的秒数
				const seconds = timeDifference % 60;

				return {
					days: days,
					hours: hours,
					minutes: minutes,
					seconds: seconds
				};
			},
			// 砍价详情
			async bargainsGoodsDetail(uid = '', id = '') {
				uni.showLoading({
					title: '加载中'
				});
				console.log(id, uid)
				console.log(uid ? uid : uni.getStorageSync('uid'), id ? id : this.detailInfo.id, '================')
				const result = await this.$http.get({
					url: this.$api.bargainsGoodsDetail,
					data: {
						// 用户id
						uid: uid ? uid : uni.getStorageSync('uid'),
						// 产品id
						bargains_id: id ? id : this.detailInfo.id,

					}
				});
				console.log(result)
				if (result.errno == 0) {
					console.log(this.detailInfo)
					this.detailInfo = result.data;
					antiThrottling.releaseKey('submit');
					// 选择规格
					this.detailInfo.timeDifference = this.formatTimeDifference(this.detailInfo.end_time)


					if (this.detailInfo.log.length) {
						this.shareList = this.detailInfo.log.map((item) => {
							return {
								userName: item.nickname,
								avatar: item.avatar,
								content: item.nickname + '帮砍了' + item.money + '元'
							}
						})
						console.log(this.shareList)
					}
					if (this.assistUid != uni.getStorageSync('uid')) {

						// 在这还要判断是否已经砍价砍了就不显示弹框
						const hasUid = this.detailInfo.log.some(item => item.pid == uni.getStorageSync('uid'));

						if (!hasUid) {	
							this.popClick()
						}
                       
					}
					this.cutDetailFn(uid)
					console.log('222')



				}
			},
			async cutYourselfKnife() {
				const result = await this.$http.get({
					url: this.$api.bargainsBargainsCut,
					data: {
						uid: uni.getStorageSync('uid'),
						order_id: this.detailInfo.order_id
					}
				});
				if (result.errno == 0) {
					antiThrottling.uniDoFunc({
						// 键名
						key: 'submit',
						success: async () => {
							//锁定
							antiThrottling.lockKey('submit');

							this.$sun.toast('砍价成功', 'none', 1500)
                         
							console.log('111')
							setTimeout(() => {
								this.mescroll?.resetUpScroll();
							}, 1000)
							// this.bargainsGoodsDetail()

						}
					});


				} else {
					this.$sun.toast(result.message);
				}
			},
			popClick() {
				this.$refs.popCode.show({
					anim: 'center',
					shadeClose: false, //false使用户不能点击其它关闭页面
					topclose: false
				});
			},


			popCodeClose() {
				this.$refs.popCode.close();
			},

		}
	}
</script>

<style lang="less" scoped>
	.bg {


		background-repeat: no-repeat;
		// position: relative;

		// padding: 7rpx;
		background-image: (var(--bg-image));
		background-size: contain;
		height: 100vh;

		.return-index {
			margin-top: 30rpx;
			margin-left: -20rpx;

			height: 76rpx;
			border-radius: 0rpx 40rpx 40rpx 0rpx;
			background: rgba(0, 0, 0, 0.6);

			image {

				height: 26rpx;
				margin-right: 8rpx;
			}

			view {
				color: #fff;
				font-size: 24rpx;
			}

			.swiper {
				margin-bottom: 10rpx;
				border-radius: 30rpx;

				width: 403rpx;
				height: 76rpx;

			}

			.swiper-item {
				.noticeImg {
					margin-right: 10rpx;
					height: 48rpx;
					width: 48rpx;
					border-radius: 50%;
				}

				width: 373rpx;
				height: 76rpx;
				line-height: 79rpx;
				text-align: center;
			}

			.swiper-list {
				margin-top: 40rpx;
				margin-bottom: 0;
			}
		}

		.card {
			margin: 50rpx 22rpx 0;

			width: 710rpx;

			border-radius: 20rpx;
			padding: 20rpx;
			background: rgb(255, 255, 255);

			.bargainingRules {
				padding: 15rpx;
				background-color: #fff;
			}

			.pendingPayDetail {

				// width: 668rpx;
				// height: 196rpx;
				border-radius: 20rpx;
				padding: 15rpx;
				background: linear-gradient(180.00deg, rgb(254, 230, 236), rgb(255, 244, 246) 100%);

				.orderPageDescribe {
					// padding-bottom: 10rpx;
					// border-bottom: 2rpx solid rgb(238, 238, 238);

					.img {
						width: 174rpx;
						height: 174rpx;
						border-radius: 20rpx;



					}


				}


			}

			.initiateBargaining {
				color: #fff;
				border-radius: 170rpx;
				width: 656rpx;
				height: 98rpx;
				background: linear-gradient(90.00deg, rgb(255, 141, 34), rgb(255, 182, 44) 100%);
			}

			.initiateBargainingRed {
				color: #fff;
				border-radius: 170rpx;
				width: 656rpx;
				height: 98rpx;
				background: linear-gradient(90.00deg, rgb(255, 43, 34), rgb(255, 44, 99) 100%);
			}
		}

		.rules {
			margin: 22rpx;
			margin-top: 30rpx;
			padding: 30rpx;
			border-radius: 20rpx;

			background: rgb(255, 255, 255);
		}

		// 二维码
		.v-pop-code {
			.v-qr-code {
				position: relative;
				padding: 42rpx 0 0rpx;
				background: transparent;
				border-radius: 10rpx;
				// width: 526rpx;

				image {
					width: 666rpx;
					height: 841rpx;
				}

				// text {
				// 	margin-top: 26rpx;
				// }
				.orderPageDescribe {
					top: 300rpx;

					z-index: 999;
					position: absolute;
					// padding-bottom: 10rpx;
					// border-bottom: 2rpx solid rgb(238, 238, 238);

					.img {
						width: 134rpx;
						height: 134rpx;
						border-radius: 20rpx;



					}


				}
			}


			.v-close-img {
				width: 82rpx;
				height: 82rpx;
				// margin-top: 46rpx;
			}
		}
	}
</style>